<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
</head>

<body>
	<!-- 提前准好一个回调函数，等着对方来调用并传参数 -->
	<input type="text" name="" id="txt">
	<ul id="result">

	</ul>
	<script>
	
		// function show(json) {
		// 	let list = document.querySelector('#result');
		// 	list.innerHTML = '';
		// 	json.s.map(item => {
		// 		let oli = document.createElement('li');
		// 		oli.innerHTML = item;
		// 		list.appendChild(oli);
		// 	})
		// }

		// window.onload = function() {
		// 	let input = document.querySelector('#txt');

		// 	input.oninput = function() {
		// 		let oS = document.createElement('script');
		// 		oS.src = `https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${this.value}&cb=show`;
		// 		document.head.appendChild(oS);
		// 	}
		// }



	</script>
	
	<script>
function ajax(options) {
	if (!options.url) { return false };
	options.data = options.data || {};
	options.dataType = options.dataType || 'text';

	let arr = [];
	for (key in options.data) {
		arr.push(`${encodeURIComponent(key)}=${encodeURIComponent(options.data[key])}`);
	}
	let strData = arr.join('&');

	let xhr = new XMLHttpRequest();
	if (options.type == 'get') {
		xhr.open('GET', options.url + '?' + strData, true); // false是同步，如果设置成同步，浏览器会给警告，浏览器会阻止使用同步
		xhr.send();
	} else {
		xhr.open('POST', options.url, true);
		xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
		xhr.send(strData);
		
	}
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
				let data = xhr.responseText;
				switch (options.dataType) {
					case 'json':
						if (window.JSON && JSON.parse) {
							data = JSON.parse(data);
						} else {
							data = eval('(' + str + ')');
						}
						break;
					case 'xml':
						data = xhr.responseXML;
						break;
				}
				options.success && options.success(data);
			} else {
				options.error && options.error(xhr);
			}
		}
	}
}

ajax({
	url: '1.php',
	data: {a:12,b:13},
	dataType: 'text',
	type: 'get',
	success: function(str) {
		console.log(str);
	},
	error: function() {
		alert('error')
	}
});

	</script>
</body>

</html>